<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ editId ? "试题修改" : "试题录入" }}</span>
      </div>

      <div class="questionForm">
        <el-form :model="questionForm" :rules="rules" ref="questionForm">
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              v-model="questionForm.subjectID"
              placeholder="请选择"
              @change="handleSubjectChange"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.id"
                :label="item.subjectName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="questionForm.catalogID" placeholder="请选择">
              <el-option
                v-for="item in catalogList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="questionForm.enterpriseID" placeholder="请选择">
              <el-option
                v-for="item in enterpriseList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" required>
            <el-row :gutter="5" style="width: 302px">
              <el-col :span="9">
                <el-form-item prop="province">
                  <el-select
                    v-model="questionForm.province"
                    placeholder="请选择"
                    @change="questionForm.city = ''"
                  >
                    <el-option
                      v-for="(item, index) in provinceList"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item prop="city">
                  <el-select v-model="questionForm.city" placeholder="请选择">
                    <el-option
                      v-for="(item, index) in cityList"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="方向：" prop="direction">
            <el-select v-model="questionForm.direction" placeholder="请选择">
              <el-option
                v-for="(item, index) in direction"
                :key="index"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group
              v-model="questionForm.questionType"
              @change="handleQuestionTypeChange"
              style="padding-top: 12px"
            >
              <el-radio
                v-for="(item, index) in this.questionType"
                :key="index"
                :label="item.value.toString()"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group
              v-model="questionForm.difficulty"
              style="padding-top: 12px"
            >
              <el-radio
                v-for="(item, index) in this.difficulty"
                :key="index"
                :label="item.value.toString()"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干：" prop="question">
            <quillEditor
              v-model="questionForm.question"
              :options="editorOption"
              @blur="handleEditorBlur('question')"
              style="margin-left: 65px"
            ></quillEditor>
          </el-form-item>
          <el-form-item label="选项：" v-if="questionForm.questionType !== '3'">
            <el-row
              :gutter="5"
              type="flex"
              class="choice-row"
              v-for="(option, index) in questionForm.options"
              :key="index"
              style="margin-top: 36px; padding-left: 50px; width: 710px"
            >
              <el-col :span="1" style="padding-top: 20px">
                <el-checkbox
                  v-model="option.isRight"
                  v-if="questionForm.questionType === '2'"
                />
                <el-radio v-model="radio" :label="index" v-else>{{
                  ""
                }}</el-radio>
              </el-col>
              <el-col :span="1">{{ option.code }}:</el-col>
              <el-col :span="10"
                ><el-input v-model="option.title"></el-input
              ></el-col>
              <el-col :span="4">
                <imageUploader v-model="option.img"></imageUploader>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="addChoice"
              type="danger"
              :disabled="questionForm.questionType === '1'"
              v-if="questionForm.questionType !== '3'"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <el-form-item label="解析视频：">
            <el-col style="width: 400px">
              <el-input v-model="questionForm.videoURL"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="答案解析：" prop="answer">
            <quillEditor
              v-model="questionForm.answer"
              :options="editorOption"
              @blur="handleEditorBlur('answer')"
              style="margin-left: 82px"
            ></quillEditor>
          </el-form-item>
          <el-form-item label="题目备注：">
            <el-col :span="24" style="width: 522px">
              <el-input
                type="textarea"
                v-model="questionForm.remarks"
              ></el-input>
            </el-col>
          </el-form-item>
          <!-- 为试题标签手动添加红星 -->
          <el-form-item
            label="试题标签："
            prop="tagArray"
            class="redStarLocation"
          >
            <el-select
              v-model="tagArray"
              placeholder="请选择试题标签"
              multiple
              filterable
              allow-create
              style="margin-left: -9px"
            >
              <el-option
                v-for="item in tagList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="submitEditedForm" v-if="editId">
              确认修改
            </el-button>
            <el-button
              type="primary"
              @click="submitForm('questionForm')"
              v-else
            >
              确认提交
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import imageUploader from '@/components/ImageUploader'
import { difficulty, questionType, direction } from '@/api/hmmm/constants'
import { provinces, citys } from '@/api/hmmm/citys'
import { list as getEnterpriseList } from '@/api/hmmm/companys'
import { list as getSubjectList } from '@/api/hmmm/subjects'
import { simple as getCatalogList } from '@/api/hmmm/directorys'
import { simple as getTagList } from '@/api/hmmm/tags'
import {
  add as addBasicQuestion,
  detail as getQuestionDetail,
  update as submitEditedQuestion
} from '@/api/hmmm/questions'

export default {
  async created () {
    this.loadSubjectList()
    this.loadEnterpriseList()
    if (this.editId) this.loadQuestionDetail()
  },
  watch: {
    // 如果单选框被清空，什么都不做。否则根据单选框的选中情况同步questionForm里options数组里的isRight值
    radio (index) {
      if (index === '') return
      this.questionForm.options.forEach((item) => {
        item.isRight = false
      })
      this.questionForm.options[index].isRight = true
    },
    // 同步试题标签下拉选单的选中情况到questionForm里，并转换数组为字符串
    tagArray (newArr) {
      this.questionForm.tags = newArr.join(',')
    }
  },
  components: {
    quillEditor,
    imageUploader
  },
  computed: {
    // 计算在城市的第二个下拉选单里的数据
    cityList () {
      const currentProvice = this.questionForm.province
      return currentProvice ? this.citys(currentProvice) : []
    }
  },
  data () {
    var checkTags = (rule, value, callback) => {
      if (!this.questionForm.tags) {
        callback(new Error('请选择或添加自定义标签'))
      } else callback()
    }
    return {
      editId: this.$route.query.id,
      subjectList: [],
      catalogList: [],
      enterpriseList: [],
      tagList: [],
      // 当前选中的标签数组，需要转换为字符串后同步到questionForm里
      tagArray: [],
      // 显示在城市的第一个下拉选单里的数据
      provinceList: this.provinces(),
      // 题型是单选时正确答案的index，与ABCD的单选框数据绑定
      radio: '',
      difficulty,
      questionType,
      direction,
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
            ['blockquote'], // 引用
            ['code-block', 'image', 'link'] // 代码块，图片，链接
          ]
        }
      },
      questionForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择市区', trigger: 'change' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干' }],
        answer: [{ required: true, message: '请输入答案解析' }],
        // 校验试题标签是否为空时，直接去questionForm里看tags是否为空字符串
        tagArray: [{ validator: checkTags, trigger: 'change' }]
      }
    }
  },
  methods: {
    // 如果是问题是简答题，需要在提交前一刻清空选择题选项里的废数据
    removeUselessOptions () {
      if (this.questionForm.questionType === '3') {
        this.questionForm.options = [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
      }
    },
    // 数据回填函数,不是所有值都是和questionForm直接绑定的，需要边检查边回填
    async loadQuestionDetail () {
      const res = (await getQuestionDetail({ id: this.editId })).data
      console.log(res)
      const form = this.questionForm
      form.subjectID = res.subjectID
      // 刷新目录和试题标签下拉选单里的数据
      this.handleSubjectChange()
      form.catalogID = res.catalogID
      form.enterpriseID = res.enterpriseID
      form.province = res.province
      form.city = res.city
      form.direction = res.direction
      form.questionType = res.questionType
      form.difficulty = res.difficulty
      form.question = res.question
      form.options = res.options
      // 返回的选项顺序是错乱的，必须先排序再渲染到页面中
      form.options.sort((a, b) => {
        if (a.code < b.code) return -1
        if (a.code > b.code) return 1
        return 0
      })
      // 获取的数据中isRight值为1和0，需要转换为true和false
      form.options.forEach((item) => {
        item.isRight = !!item.isRight
      })
      // 单选情况下，通过改变radio值来同步单选框的选中情况
      if (form.questionType === '1') {
        this.radio = form.options.findIndex((item) => item.isRight === true)
      }
      form.videoURL = res.videoURL
      form.answer = res.answer
      form.remarks = res.remarks
      // 通过改变tagArray来同步页面上显示的试题标签
      this.tagArray = res.tags.split(',')
      // 以下为修改表单时questionForm里独有的属性
      form.id = res.id
      form.number = res.number
      form.creatorID = res.creatorID
      form.addDate = res.addDate
    },
    // 在富文本编辑器失去焦点时进行表单校验
    handleEditorBlur (location) {
      this.$refs.questionForm.validateField(location)
    },
    async loadTagList () {
      this.tagList = (
        await getTagList({ subjectID: this.questionForm.subjectID })
      ).data
    },
    async loadEnterpriseList () {
      this.enterpriseList = (
        await getEnterpriseList({ pagesize: 10000 })
      ).data.items
    },
    async loadSubjectList () {
      this.subjectList = (await getSubjectList({ pagesize: 10000 })).data.items
    },
    async loadCatalogList () {
      this.catalogList = (
        await getCatalogList({ subjectID: this.questionForm.subjectID })
      ).data
    },
    // 学科发生变化时更新目录和试题标签下拉选单里的选项
    handleSubjectChange () {
      this.loadCatalogList()
      this.loadTagList()
    },
    provinces,
    citys,
    // 问题类型发生变化时，清空单选框和单选框里的值。清空单选框时会触发radio的watcher，需要进行特殊处理
    handleQuestionTypeChange () {
      this.questionForm.options.forEach((item) => {
        item.isRight = false
      })
      this.radio = ''
    },
    addChoice () {
      const code = String.fromCharCode(
        this.questionForm.options.slice(-1)[0].code.charCodeAt(0) + 1
      )
      this.questionForm.options.push({
        code,
        title: '',
        img: '',
        isRight: false
      })
    },
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            this.removeUselessOptions()
            await addBasicQuestion(this.questionForm)
            this.$message.success('提交成功')
            this.$router.push('/questions/list')
          } catch (err) {
            this.$message.error('提交失败')
          }
        } else {
          this.$message.error('提交失败，请填写所有必填项后重试')
          return false
        }
      })
    },
    submitEditedForm () {
      this.$refs.questionForm.validate(async (valid) => {
        if (valid) {
          try {
            this.removeUselessOptions()
            // 编辑模式下videoURL和remarks为必填项，如果为空则帮用户填写
            this.questionForm.videoURL = this.questionForm.videoURL || '无'
            this.questionForm.remarks = this.questionForm.remarks || '无'
            await submitEditedQuestion(this.questionForm)
            this.$message.success('修改成功')
            this.$router.push('/questions/list')
          } catch (err) {
            this.$message.error('修改失败')
          }
        } else {
          this.$message.error('提交失败，请填写所有必填项后重试')
          return false
        }
      })
    }
  }
}
</script>

<style>
.redStarLocation .el-form-item__label::before {
  margin-right: 4px;
  content: "*";
  color: #f56c6c;
}

.preview {
  width: 100px;
  height: 60px;
}

.choice-row {
  line-height: 0;
  align-items: center;
}

.ql-toolbar {
  height: 40px;
  padding: 0 5px !important;
}
.ql-editor {
  height: 400px;
}
.container {
  display: flex;
  justify-content: center;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  margin-left: 10px;
}
</style>
